/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-12-06
 * Time:16:22
 */

//创建节点类
class Node{
    public int val;
    public Node next;
    public Node(int val) {
        this.val = val;
        this.next = null;
    }
}


public class MyLinkedList {
    public Node head;

    public void createdList(){
        Node node1 = new Node(2);
        Node node2 = new Node(2);
        Node node3 = new Node(5);
        Node node4 = new Node(2);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        this.head = node1;

    }
    public void display(){
        Node cur = this.head;
        while (cur!= null){
            System.out.print(cur.val + " -> ");
            cur = cur.next;
        }
        System.out.print("null");
        System.out.println();
    }

    public int size(){
        if (this.head == null){
            return -1;
        }
        Node cur = this.head;
        int count = 0;
        while (cur != null){
            count++;
            cur = cur.next;
        }
        return count;
    }


    public boolean contains(int key){
        if (this.head == null){
            return false;
        }
        Node cur = this.head;
        while (cur != null){
            if (cur.val == key){
                return true;
            }
            cur = cur.next;
        }
        return false;
    }
    public void removeAllKey(int key){
        // 处理头节点是key的情况
        while (this.head.val == key){
            this.head = this.head.next;
        }
        if (this.head == null){
            return;
        }
        Node prev = this.head;
        Node cur = this.head.next;
        while (cur != null){
            if (cur.val == key){
                // 当cur还是key的时候prev不进行调整
                prev.next = cur.next;
                cur = cur.next;
            }else {
                prev = cur;
                cur = cur.next;
            }
        }
    }
}
